using System;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace RevitForge.Services
{
    public class Message
    {
        [JsonProperty("role")]
        public string Role { get; set; }

        [JsonProperty("content")]
        public string Content { get; set; }
    }

    public class DeepSeekService
    {
        private readonly HttpClient _httpClient;
        private string _apiKey;
        private const string API_URL = "https://api.deepseek.com/v1/chat/completions";
        private List<Message> _messageHistory;

        public DeepSeekService(string apiKey)
        {
            _apiKey = apiKey;
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
            _messageHistory = new List<Message>();
        }

        public void UpdateApiKey(string newApiKey)
        {
            _apiKey = newApiKey;
            _httpClient.DefaultRequestHeaders.Remove("Authorization");
            _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
        }

        public void ClearHistory()
        {
            _messageHistory.Clear();
        }

        public async Task<string> ChatAsync(string userMessage, string systemPrompt = null)
        {
            try
            {
                if (systemPrompt != null && _messageHistory.Count == 0)
                {
                    _messageHistory.Add(new Message { Role = "system", Content = systemPrompt });
                }

                _messageHistory.Add(new Message { Role = "user", Content = userMessage });

                var requestBody = new
                {
                    model = "deepseek-chat",
                    messages = _messageHistory.ToArray(),
                    stream = false,
                    temperature = 0.7
                };

                var jsonContent = JsonConvert.SerializeObject(requestBody, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    Formatting = Formatting.None
                });

                StringContent content = new StringContent(
                    jsonContent,
                    System.Text.Encoding.UTF8,
                    "application/json");

                HttpResponseMessage response = await _httpClient.PostAsync(API_URL, content);

                if (!response.IsSuccessStatusCode)
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    throw new Exception($"API响应错误 ({(int)response.StatusCode}): {errorContent}");
                }

                string responseBody = await response.Content.ReadAsStringAsync();
                var responseObject = JsonConvert.DeserializeObject<dynamic>(responseBody);

                if (responseObject?.choices == null || responseObject.choices.Count == 0)
                {
                    throw new Exception("API响应内容为空或格式错误");
                }

                string assistantResponse = responseObject.choices[0].message.content?.ToString();
                _messageHistory.Add(new Message { Role = "assistant", Content = assistantResponse });

                return assistantResponse;
            }
            catch (Exception ex)
            {
                throw new Exception($"调用DeepSeek API失败: {ex.Message}");
            }
        }

        public async Task<string> GenerateCodeAsync(string prompt)
        {
            const string REVIT_SYSTEM_PROMPT = @"你是一个专业的Revit插件开发助手，
                        根据用户的需求生成实现了IExternalCommand接口的完整C#代码。要求：
                        1.除了代码之外的东西不要回复
                        2.包含完整事务处理,处理异常,添加必要注释
                        3.实现接口的类名必须以Command结尾
                        4.添加Description静态属性描述按钮功能
                        5.添加ButtonName静态属性描述按钮名字(四个字)";
                return await ChatAsync(prompt, REVIT_SYSTEM_PROMPT);
        }
    }
}